package handler

import (
	"context"
	"gitee.com/banyanhouse/distill-infra/validator"
	"gitee.com/banyanhouse/distill-infra/web"
	"gitee.com/banyanhouse/distill-micro-grpc-hystrix/micro-gateway/Services"
	"gitee.com/banyanhouse/distill-micro-grpc-hystrix/micro-gateway/utils"
	irisContext "github.com/kataras/iris/context"
	"github.com/micro/go-micro/v2/metadata"
)

func PannicIfError(err error) {
	if err != nil {
		panic(err)
	}
}

func GetProdDetail(ctx irisContext.Context) {
	var (
		res web.Res
	)
	var prodReq Services.ProdsRequest
	pid := ctx.Params().GetInt32Default("pid", 0)
	prodReq.ProdId = pid
	prodService := ctx.Values().Get("prodService").(Services.ProdService)
	prodDetailResponse, err := prodService.GetProdDetail(context.Background(), &prodReq)
	//err = errors.New("伪造异常") // 测试统一异常处理拦截middleware
	PannicIfError(err)
	// 响应REST数据
	res = web.Res{
		Code:    web.ResCodeOk,
		Message: "商品详情",
		Data:    prodDetailResponse.GetData(),
	}
	ctx.JSON(&res)
}

func ProdHandler(ctx irisContext.Context) {
	var (
		res web.Res
		err error
	)
	prodService := ctx.Values().Get("prodService").(Services.ProdService)

	var prodsRequest Services.ProdsRequest
	// 接收客户端请求，以json形式加载到请求体
	err = ctx.ReadJSON(&prodsRequest)
	// 验证请求体内容
	validatorErr := validator.ValidateStruct(&prodsRequest)
	if err != nil || validatorErr != nil {
		utils.ErrRes(err, validatorErr, &res)
		ctx.JSON(&res)
		return
	}
	//// 调用微服务接口
	//// 这里加入一个熔断
	//// 第一步配置一个config
	//configA := hystrix.CommandConfig {
	//	Timeout: 1000,
	//}
	//// 配置command
	//var prodsList *Services.ProdListResponse
	//hystrix.ConfigureCommand("getprods", configA)
	//err = hystrix.Do("getprods", func() error {
	//	prodsList, err = prodService.GetProdsList(context.Background(), &prodsRequest)
	//	return err
	//}, func(err error) error {
	//	// 降级函数
	//	prodsList, err = defaultProds()
	//	return err
	//})

	m := map[string]string{
		"datacenter": "prodService",
	}

	newContext := metadata.NewContext(context.Background(), m)

	prodsList, err := prodService.GetProdsList(newContext, &prodsRequest)
	if err != nil {
		utils.ErrRes(err, nil, &res)
		ctx.JSON(&res)
		return
	}
	// 响应REST数据
	res = web.Res{
		Code:    web.ResCodeOk,
		Message: "商品列表",
		Data:    prodsList.GetData(),
	}
	ctx.JSON(&res)

}
